import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_framework/utils/screen_ui.dart';

class StreamBuilderPage extends StatefulWidget {
  @override
  _StreamBuilderPageState createState() => _StreamBuilderPageState();
}

class _StreamBuilderPageState extends State<StreamBuilderPage> {
  final StreamController _keybordCtrl = StreamController.broadcast();
  final StreamController _sourceNumCtrl = StreamController.broadcast();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _keybordCtrl.close();
    _sourceNumCtrl.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // 使用一个 stream transform 转接口，来实现stream 的转接数据
        title: StreamBuilder(
            stream: _sourceNumCtrl.stream.transform(MySourceStreamCtrl()),
            builder: (ctx, snapshot) {
              if (snapshot.connectionState == ConnectionState.none) {
                // 没有数据流
                return const Text('准备开始!');
              }
              if (snapshot.connectionState == ConnectionState.waiting) {
                // 等待数据流
                return const Text('准备开始!');
              } else if (snapshot.connectionState == ConnectionState.done) {
                return const Text('数据流完成 done');
              } else {
                if (snapshot.hasData) {
                  return Text('当前积分：${snapshot.data}');
                } else {
                  return Text('报错：${snapshot.error}');
                }
              }
            }),
      ),
      body: Stack(
        children: [
          ...List.generate(
            3,
            (index) => Topic(
              keybordCtrl: _keybordCtrl,
              sourceNumCtrl: _sourceNumCtrl,
            ),
          ).toList(),
          KeyPad(keybordCtrl: _keybordCtrl, sourceNumCtrl: _sourceNumCtrl),
        ],
      ),
    );
  }
}

class KeyPad extends StatefulWidget {
  const KeyPad(
      {super.key, required this.keybordCtrl, required this.sourceNumCtrl});

  final StreamController keybordCtrl;
  final StreamController sourceNumCtrl;

  @override
  _KeyPadState createState() => _KeyPadState();
}

class _KeyPadState extends State<KeyPad> {
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.bottomCenter,
      child: GridView.builder(
          // 是否缩放视图
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          itemCount: 9,
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, childAspectRatio: 2 / 1),
          itemBuilder: (ctx, index) {
            return ElevatedButton(
                style: ButtonStyle(
                    backgroundColor:
                        MaterialStateProperty.all(Colors.primaries[index]),
                    shape:
                        MaterialStateProperty.all(const BeveledRectangleBorder(
                      borderRadius: BorderRadius.all(Radius.circular(0)),
                    ))),
                onPressed: () {
                  widget.keybordCtrl.add(index + 1);
                  // 按一次键盘扣两分
                  // widget.sourceNumCtrl.add(-2);
                },
                child: Text(
                  '${index + 1}',
                  style: const TextStyle(fontSize: 20),
                ));
          }),
    );
  }
}

class MySourceStreamCtrl implements StreamTransformer {
  var _sum = 0;
  StreamController streamController = StreamController();

  @override
  Stream bind(Stream stream) {
    // TODO: implement bind
    stream.listen((event) {
      _sum += event as int;
      streamController.add(_sum);
    });
    return streamController.stream;
  }

  @override
  StreamTransformer<RS, RT> cast<RS, RT>() {
    return StreamTransformer.castFrom(this);
  }
}

class Topic extends StatefulWidget {
  final StreamController keybordCtrl;
  final StreamController sourceNumCtrl;

  const Topic(
      {super.key, required this.keybordCtrl, required this.sourceNumCtrl});

  @override
  _TopicState createState() => _TopicState();
}

class _TopicState extends State<Topic> with SingleTickerProviderStateMixin {
  int a = 0, b = 0;
  late Color color;
  late int x;
  late final AnimationController _animationCtrl = AnimationController(
      vsync: this, duration: Duration(seconds: Random().nextInt(8) + 4));

  // 每次计算完， 重新构建一遍reset
  reset() {
    a = Random().nextInt(9);
    b = Random().nextInt(9 - a);
    color = Colors.primaries[Random().nextInt(18)].withOpacity(0.3);
    x = Random().nextInt((ScreenUI.width - 80).floor());
    _animationCtrl.duration = Duration(seconds: Random().nextInt(8) + 4);
    _animationCtrl.reset();
    _animationCtrl.forward();
  }

  @override
  void initState() {
    // TODO: implement initState
    reset();
    _animationCtrl.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        // 落地 没有回答内容，扣分
        widget.sourceNumCtrl.add(-5);
        reset();
      }
    });
    widget.keybordCtrl.stream.listen((event) {
      if (event == a + b) {
        // 输入正确
        widget.sourceNumCtrl.add(10);
        reset();
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _animationCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
        animation: _animationCtrl,
        builder: (ctx, child) {
          return Positioned(
              top: -100 + (ScreenUI.height - 150) * _animationCtrl.value,
              left: x.toDouble(),
              child: Container(
                width: 80,
                height: 30,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  color: color,
                ),
                child: Text(
                  '$a+$b',
                  style: const TextStyle(fontSize: 14, color: Colors.black),
                ),
              ));
        });
  }
}
